package com.lyq.interaction.config;

import com.lyq.interaction.InteractionWebApplication;
import com.lyq.interaction.controller.WebSocketController;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Resource
    private WebSocketController webSocketController;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketController, "/wsMessage")
                .addInterceptors(new HttpSessionHandshakeInterceptor());
    }
}

//class MyHttpSessionHandshakeInterceptor extends HttpSessionHandshakeInterceptor{
//    @Override
//    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
//                               WebSocketHandler wsHandler, @Nullable Exception ex) {
//        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
//        HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse();
//        servletResponse.setHeader("sec-websocket-protocol", servletRequest.getHeader("sec-websocket-protocol"));
//    }
//}